﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MishraReader.ViewModels;

#if !WINRT

using System.Windows;
#else
using Windows.UI.Xaml;

#endif

namespace MishraReader.Windows
{
    public class DialogBoxBase : Window
    {
        static DialogBoxBase()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DialogBoxBase), new FrameworkPropertyMetadata(typeof(DialogBoxBase)));
        }

        public DialogBoxBase()
        {
            WindowStyle = WindowStyle.None;
            AllowsTransparency = true;
            ResizeMode = ResizeMode.NoResize;
            Style = Application.Current.Resources["DialogBoxBase"] as Style;
            WindowStartupLocation = WindowStartupLocation.Manual;
            ShowInTaskbar = false;
            Topmost = true;
            Height = Application.Current.MainWindow.Height;
            Width = Application.Current.MainWindow.Width;

            if (Application.Current.MainWindow.WindowState == WindowState.Maximized)
            {
                Top = 0;
                Left = 0;
            }
            else
            {
                Top = Application.Current.MainWindow.Top;
                Left = Application.Current.MainWindow.Left;
            }

            Owner = Application.Current.MainWindow;
            Loaded += DialogBoxBase_Loaded;
        }

        protected override void OnClosed(EventArgs e)
        {
            var vm = DataContext as ViewModelBase;
            if (vm != null)
            {
                vm.Cleanup();
                DataContext = null;
            }

            base.OnClosed(e);
        }

        private void DialogBoxBase_Loaded(object sender, RoutedEventArgs e)
        {
            if (AllowsTransparency)
            {
                Height = Application.Current.MainWindow.Height;
                Width = Application.Current.MainWindow.Width;

                if (Application.Current.MainWindow.WindowState == WindowState.Maximized)
                {
                    Top = 0;
                    Left = 0;
                }
                else
                {
                    Top = Application.Current.MainWindow.Top;
                    Left = Application.Current.MainWindow.Left;
                }
            }
            else
            {
                SizeToContent = SizeToContent.WidthAndHeight;
                WindowStartupLocation = WindowStartupLocation.CenterOwner;

                // Calc top 
                Top = Application.Current.MainWindow.Top + (Application.Current.MainWindow.Height - Height)/2;
                Left = Application.Current.MainWindow.Left + (Application.Current.MainWindow.Width - Width)/2;
            }
        }
    }
}